﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ECSE6770.Models;

namespace ECSE6770
{
    public static class ContextManager
    {
        private const string KEY = "ECSE6770.ContextManager.CurrentContext";
        private const string USER_KEY = "ECSE6770.ContextManager.CurrentUser";
        private static readonly object padlock = new object();

        public static EntitiesContainer CurrentDb
        {
            get
            {
                lock (padlock)
                {
                    EntitiesContainer container = HttpContext.Current.Items[KEY] as EntitiesContainer;
                    if (container == null)
                    {
                        container = new EntitiesContainer();
                        HttpContext.Current.Items[KEY] = container;
                    }
                    return container;
                }
            }
        }

        public static UserInterop LoadUserInterop(string userName)
        {
            return CurrentDb.UserInterops.First(u => u.UserName == userName);
        }

        public static UserProfile CurrentUser
        {
            get
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    UserProfile profile = HttpContext.Current.Items[USER_KEY] as UserProfile;
                    if (profile == null)
                    {
                        profile = new UserProfile(HttpContext.Current.User.Identity.Name);
                        HttpContext.Current.Items[KEY] = profile;
                    }
                    return profile;
                }
                else
                    return null;
            }
        }

        public static void EndRequest()
        {
            CurrentDb.Dispose();
        }
    }
}